package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
//！有一个bug，每次页面刷新都会数量加1 原因：跳往item.jsp的itemFormServlet
@WebServlet(name = "UpdateCartServlet", urlPatterns = {"/updateCart"})
//手动更改的数量更新
public class UpdateCartServlet extends HttpServlet {
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    private CartService cartService;
    public UpdateCartServlet()
    {
        cartService=new CartService();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session= req.getSession();
        Account loginAccount=(Account) session.getAttribute("loginAccount");

        session.setAttribute("action","updateCart");

        Cart cart=(Cart) session.getAttribute("cart");
        //迭代器遍历，用的是Cart内定义的函数
        Iterator<CartItem>cartItems= cart.getAllCartItems();
        while (cartItems.hasNext())
        {
            CartItem cartItem=cartItems.next();
            String itemId=cartItem.getItem().getItemId();
            try{
                //用户在购物车页面更改数量,获取表单中输入的数量
                String QuantityInput=req.getParameter(itemId);
                int quantity=Integer.parseInt(QuantityInput);
                cartService.updateCart(loginAccount.getUsername(),itemId,quantity);
                //如果改变后数量小于1，则直接在购物车删除，不再显示
                if(quantity<1)
                {
                    cartService.removeItem(loginAccount.getUsername(), itemId);
                }
            }
            catch (Exception e)
            {

            }
        }
        resp.sendRedirect("cartForm");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //直接访问为空购物车
        resp.sendRedirect("cartForm");
    }
}


